package com.vhall.component.service.pay.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.vhall.component.dao.pay.PaymentOrderMapper;
import com.vhall.component.entity.pay.entity.PaymentOrderEntity;
import com.vhall.component.service.pay.PaymentOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * @author xuyongzheng
 * @since 2020/10/22
 **/
@Slf4j
@Service
public class PaymentOrderServiceImpl implements PaymentOrderService {

    @Autowired
    PaymentOrderMapper paymentOrderMapper;

    @Override
    public PaymentOrderEntity findByBizOrderId(String bizOrderNo) {
        QueryWrapper<PaymentOrderEntity> query = new QueryWrapper<>();
        query.eq("biz_order_no", bizOrderNo);

        return paymentOrderMapper.selectOne(query);
    }

    @Override
    public int updateOpenId(String bizOrderNo, String openId) {

        PaymentOrderEntity entity = new PaymentOrderEntity();
        entity.setOpenId(openId);
        entity.setUpdatedAt(LocalDateTime.now());

        UpdateWrapper<PaymentOrderEntity> wrapper = new UpdateWrapper<>();
        wrapper.eq("biz_order_no", bizOrderNo);

        return paymentOrderMapper.update(entity, wrapper);
    }

    @Override
    public int updateById(PaymentOrderEntity entity) {
        return paymentOrderMapper.updateById(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int doPayed(String bizNo, String tradeNo, String channel, String serviceCode, LocalDateTime payTime) {

        PaymentOrderEntity order = new PaymentOrderEntity();
        order.setStatus("SUCCESS");
        order.setTradeNo(tradeNo);
        order.setChannel(channel);
        order.setServiceCode(serviceCode);
        order.setPayTime(payTime);
        return paymentOrderMapper.update(order, new UpdateWrapper<PaymentOrderEntity>().eq("biz_order_no", bizNo));

    }

    @Override
    public PaymentOrderEntity create(PaymentOrderEntity entity) {
        LocalDateTime occurT = LocalDateTime.now();
        entity.setCreatedAt(occurT);
        entity.setUpdatedAt(occurT);
        paymentOrderMapper.insert(entity);
        return entity;
    }

}
